package com.appkubes.portal.admin.application.auth.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.common.utils.UUIDUtils;
import com.appkubes.portal.admin.application.auth.service.KeyCloakService;
import com.appkubes.portal.admin.application.auth.service.KeyCloakUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.representations.idm.CredentialRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class KeyCloakUserServiceImpl implements KeyCloakUserService {
    @Resource
    KeyCloakService keyCloakService;

    @Override
    public UserRepresentation getUserRepresentation(String username) {
        UserRepresentation getUser = keyCloakService.getRealmResource()
                .users()
                .search(username)
                .get(0);
        return getUser;
    }

    @Override
    public UserRepresentation getUserRepresentationById(String userId) {
        UserResource userResource = keyCloakService.getUserResource(userId);
        return userResource.toRepresentation();
    }

    @Override
    public IPage<UserRepresentation> getPages(Integer pageNo, Integer pageSize) {
        IPage<UserRepresentation> page = new Page<UserRepresentation>();

        Integer current = (pageNo - 1) * pageSize;

        page.setCurrent(Long.valueOf(current));
        page.setSize(pageSize);

        List<UserRepresentation> records = keyCloakService.getRealmResource()
                .users()
                .list(current, pageSize);
        page.setRecords(records);

        //获取记录总数
        Integer total = keyCloakService.getRealmResource().users().count();
        page.setTotal(total);

        return page;
    }

    //创建用户
    @Override
    public UserRepresentation createUser(String username, String password) {
        // 进入Realm
        RealmResource realmResource = keyCloakService.getRealmResource();
        // 新建用户
        UserRepresentation user = new UserRepresentation();
        // 设置登录账号
        user.setUsername(username);
        user.setId(UUIDUtils.getUUID()); //指定UUID
        // 设置账号“启用”
        user.setEnabled(true);
        // 设置密码
        List<CredentialRepresentation> credentials = new ArrayList<CredentialRepresentation>();
        CredentialRepresentation cr = createCredentialRepresentation(password);
        credentials.add(cr);
        user.setCredentials(credentials);
        // 创建用户
        Response result = realmResource.users().create(user);
        if (result.getStatus() > 300) {
            //存在错误
            log.warn("create user fail:" + result.getStatus() + ", reason:" + result.getStatusInfo().getReasonPhrase());
            throw new BusinessException("创建用户错误");
        }
        // 根据 username 查找用户
        UserRepresentation createUser = getUserRepresentation(username);
        return createUser;
    }

    //删除用户
    @Override
    public Response deleteUser(String username) {
        RealmResource realmResource = keyCloakService.getRealmResource();
        UserRepresentation user = this.getUserRepresentation(username);
        Response result = realmResource.users().delete(user.getId());
        return result;
    }

    @Override
    public Response deleteById(String userId) {
        RealmResource realmResource = keyCloakService.getRealmResource();
        Response result = realmResource.users().delete(userId);
        return result;
    }

    //重置密码
    @Override
    public Boolean resetPassword(String userId, String password) {
        try {
            CredentialRepresentation cr = createCredentialRepresentation(password);
            keyCloakService.getUserResource(userId).resetPassword(cr);
            return true;
        } catch (Exception e) {
            log.error("resetPassword error: " + userId, e);
            throw new BusinessException("修改密码错误");
        }
    }

    //设置用户状态
    @Override
    public void setEnable(String userId, Boolean enabled) {
        RealmResource realmResource = keyCloakService.getRealmResource();
        UserRepresentation user = new UserRepresentation();
        user.setEnabled(enabled);
        realmResource.users().get(userId).update(user);
        return;
    }


    //创建密码认证
    CredentialRepresentation createCredentialRepresentation(String password) {
        CredentialRepresentation cr = new CredentialRepresentation();
        cr.setType(CredentialRepresentation.PASSWORD);
        cr.setValue(password);
        cr.setTemporary(false);
        return cr;
    }
}
